﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Studio77.PopBall.Core;
using Studio77.PopBall.Utils;
using Microsoft.Phone.Tasks;
using Studio77.PopBall.Views;
using System.Windows.Threading;

namespace Studio77.PopBall
{
    public partial class MainPage : PhoneApplicationPage
    {
        int[,] datas = new int[GameStatics.RowCount, GameStatics.ColumnCount];
        MainPageItem[,] gameItems = new MainPageItem[GameStatics.RowCount, GameStatics.ColumnCount];
        Random r = new Random(DateTime.Now.Millisecond);
        DispatcherTimer blingTimer;

        // 构造函数
        public MainPage()
        {
            InitializeComponent();
            isOnGift = false;
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);


            //清除页面堆栈
            try
            {
                for (int i = 0; i < 4; i++)
                {
                    NavigationService.RemoveBackEntry();
                }
            }
            catch
            { }

            this.txtHighScore.Text = StageManager.Instance.HighScore.ToString();

            //继续游戏判断逻辑
            if (StageManager.Instance.SaveData != null)
            {
                this.btnContinue.IsEnabled = true;
                this.txtContinue.Text = "CONTINUE\n" + "STAGE-" + StageManager.Instance.SaveData.StageIndex;
            }
            else
            {
                this.btnContinue.IsEnabled = false;
                this.txtContinue.Text = "CONTINUE";
            }

            //播放背景音乐
            AudioPlayHelper.PlayBackground();

            if (e.NavigationMode == System.Windows.Navigation.NavigationMode.New)
            {
                //显示canvas
                ShowBlingItems();
                this.StoryboardVersionRound.RepeatBehavior = RepeatBehavior.Forever;
                this.StoryboardVersionRound.Begin();
            }
        }

        private void ShowBlingItems()
        {
            //初始化
            for (int i = 0; i < GameStatics.RowCount; i++)
            {
                for (int j = 0; j < GameStatics.ColumnCount; j++)
                {
                    datas[i, j] = 0;
                    gameItems[i, j] = null;
                }
            }

            for (int i = 0; i < GameStatics.RowCount; i++)
            {
                for (int j = 0; j < GameStatics.ColumnCount; j++)
                {
                    MainPageItem item = new MainPageItem();
                    int type = r.Next(5) + 1;
                    datas[i, j] = type;
                    item.SetType(type);
                    Canvas.SetTop(item, i * GameStatics.ItemHeight);
                    Canvas.SetLeft(item, j * GameStatics.ItemWidth);
                    gameItems[i, j] = item;
                    this.canvasDots.Children.Add(item);
                }
            }

            blingTimer = new DispatcherTimer();
            blingTimer.Interval = TimeSpan.FromMilliseconds(800);
            blingTimer.Tick += (object sender, EventArgs e) =>
            {
                //随机选出三个点，进行bling
                for (int i = 0; i < 5; i++)
                {
                    int row = r.Next(GameStatics.RowCount);
                    int column = r.Next(GameStatics.ColumnCount);
                    if (gameItems[row, column] != null)
                    {
                        gameItems[row, column].Bling(r.Next(500));
                    }
                }
            };
            blingTimer.Start();
        }

        private void Button_Click_1(object sender, System.Windows.RoutedEventArgs e)
        {
            bool isStart = true;
            if (StageManager.Instance.SaveData != null)
            {
                if (MessageBox.Show("Are you sure to start a new game? The lastest game record will be lost.", "Tip", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                {
                    isStart = false;
                }
            }
            if (isStart)
            {
                SoundManager.PlayEffect(SoundManager.buttonClick);
                StageManager.Instance.LaunchCount++;
                // 在此处添加事件处理程序实现。
                this.NavigationService.Navigate(new Uri("/Pages/GamePage.xaml?IsNewGame=1", UriKind.RelativeOrAbsolute));
            }
        }

        private void btnContinue_Click_1(object sender, RoutedEventArgs e)
        {
            SoundManager.PlayEffect(SoundManager.buttonClick);
            StageManager.Instance.LaunchCount++;
            // 在此处添加事件处理程序实现。
            this.NavigationService.Navigate(new Uri("/Pages/GamePage.xaml?IsNewGame=0", UriKind.RelativeOrAbsolute));
        }

        private void btnOpenxlive_Click_1(object sender, RoutedEventArgs e)
        {
            SoundManager.PlayEffect(SoundManager.buttonClick);
            //if (XLiveGameManager.CurrentSession != null && XLiveGameManager.CurrentSession.IsValid)
            //{
            //    OpenXLive.Silverlight.XLiveUIManager.ShowLeaderboard();
            //}
        }

        bool isOnGift = false;

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            if (isOnGift)
            {
                this.StoryboardHidePackage.Begin();
                isOnGift = false;
                e.Cancel = true;
            }
            base.OnBackKeyPress(e);
        }

        private void btnGift_Click_1(object sender, RoutedEventArgs e)
        {
            isOnGift = true;
            this.StoryboardShowPackage.Begin();
        }

        private void btnGetMB_Click_1(object sender, RoutedEventArgs e)
        {
            MarketplaceReviewTask marketplaceReviewTask = new MarketplaceReviewTask();
            marketplaceReviewTask.Show();
            StageManager.Instance.IsCommented = true;
            StageManager.Instance.IsDoNewUserTask = true;

            //增加30个魔法球
            StageManager.Instance.MagicBallCount += 30;

            this.btnGetMB.Content = "Already Get";
            this.btnGetMB.IsEnabled = false;
            //this.btnGift.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void btnCloseGift_Click_1(object sender, RoutedEventArgs e)
        {
            isOnGift = false;
            this.StoryboardHidePackage.Begin();
        }
    }
}